package com.hwpt.hwaccount.core.utils;

import android.content.Context;
import android.net.Uri;
import android.database.Cursor;
import android.provider.OpenableColumns;
import android.webkit.MimeTypeMap;

import com.hwpt.hwaccount.core.data.local.entity.ImageMetaData;

import java.io.InputStream;
import java.security.MessageDigest;

/**
 * 图片元数据工具类
 */
public class ImageMetaDataUtil {
    
    private Context context;
    
    public ImageMetaDataUtil(Context context) {
        this.context = context.getApplicationContext();
    }
    
    /**
     * 从Uri获取图片元数据
     * @param imageUri 图片URI
     * @return 图片元数据对象，如果获取失败返回null
     */
    public ImageMetaData getImageMetaData(Uri imageUri) {
        try {
            String fileName = getFileNameFromUri(imageUri);
            long fileSize = getFileSizeFromUri(imageUri);
            String fileMd5 = calculateFileMd5(imageUri);
            String mimeType = getMimeTypeFromUri(imageUri);
            
            return new ImageMetaData(fileName, fileSize, fileMd5, mimeType);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    
    /**
     * 从Uri获取文件名
     */
    private String getFileNameFromUri(Uri uri) {
        String result = null;
        if (uri.getScheme().equals("content")) {
            try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
                    if (nameIndex != -1) {
                        result = cursor.getString(nameIndex);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        
        if (result == null) {
            result = uri.getLastPathSegment();
        }
        
        return result != null ? result : "unknown_image_" + System.currentTimeMillis();
    }
    
    /**
     * 从Uri获取文件大小
     */
    private long getFileSizeFromUri(Uri uri) {
        if (uri.getScheme().equals("content")) {
            try (Cursor cursor = context.getContentResolver().query(uri, null, null, null, null)) {
                if (cursor != null && cursor.moveToFirst()) {
                    int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
                    if (sizeIndex != -1) {
                        return cursor.getLong(sizeIndex);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 0;
    }
    
    /**
     * 计算文件的MD5值
     */
    private String calculateFileMd5(Uri uri) {
        try (InputStream inputStream = context.getContentResolver().openInputStream(uri)) {
            if (inputStream == null) {
                return "";
            }
            
            MessageDigest digest = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[8192];
            int read;
            
            while ((read = inputStream.read(buffer)) > 0) {
                digest.update(buffer, 0, read);
            }
            
            byte[] md5Bytes = digest.digest();
            StringBuilder sb = new StringBuilder();
            for (byte b : md5Bytes) {
                sb.append(String.format("%02x", b));
            }
            
            return sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
    
    /**
     * 从Uri获取MIME类型
     */
    private String getMimeTypeFromUri(Uri uri) {
        String mimeType = null;
        
        if (uri.getScheme().equals("content")) {
            mimeType = context.getContentResolver().getType(uri);
        }
        
        if (mimeType == null) {
            String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri.toString());
            mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension.toLowerCase());
        }
        
        return mimeType != null ? mimeType : "application/octet-stream";
    }
}